from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.shortcuts import redirect
from Usuarios.forms import RegistroUsuarioForm, EditarPasswordForm, LoginForm, EditarUsuarioForm

def registrarse(request):
	if request.method == 'GET':
		return render_to_response(
			'usuarios/registrar.html',
			{'form': RegistroUsuarioForm(), 'usuario': request.user},
			context_instance=RequestContext(request)
		)
	elif request.method == 'POST':
		form = RegistroUsuarioForm(data=request.POST)
		if form.is_valid():
			form.save()
			return redirect('/usuarios/login/')
	return redirect('/proyectos/')

@login_required
def editar(request):
	if request.method == 'GET':
		return render_to_response(
			'usuarios/editar.html',
			{'form': EditarUsuarioForm(instance=request.user),
			 'usuario': request.user},
			context_instance=RequestContext(request)
		)
	elif request.method == 'POST':
		form = EditarUsuarioForm(data=request.POST, instance=request.user)
		if form.is_valid():
			form.save()
		else:
			raise Exception(form.error_messages)
	return redirect('/proyectos/')

@login_required
def editar_password(request):
	if request.method == 'GET':
		return render_to_response(
			'usuarios/editar_pass.html',
			{'form': EditarPasswordForm(user=request.user),
			 'usuario': request.user},
			context_instance=RequestContext(request)
		)
	elif request.method == 'POST':
		form = EditarPasswordForm(user=request.user, data=request.POST)
		if form.is_valid():
			form.save()
		else:
			raise Exception(form.error_messages)
	return redirect('/proyectos/')

def loginauth(request):
	if request.method == 'GET':
		try:
			nextpath = request.GET['next']
		except Exception:
			nextpath = None

		return render_to_response(
			'usuarios/login.html',
			{'form': LoginForm(), 'usuario': request.user, 'nextpath': nextpath},
			context_instance=RequestContext(request)
		)
	elif request.method == 'POST':
		form = LoginForm(data=request.POST)
		if form.is_valid():
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']
			user = authenticate(username=username, password=password)

			try:
				nextpath = form.data['nextpath']
			except Exception:
				nextpath = None

			if user is not None:
				if user.is_active:
					login(request, user=user)
					return redirect(nextpath if nextpath else '/proyectos/')
				else:
					return redirect('/usuarios/login/?next=%s' % nextpath if nextpath else '/usuarios/login/')
			else:
				return redirect('/usuarios/login/?next=%s' % nextpath if nextpath else '/usuarios/login/')
	return redirect('/proyectos/')

def logoutauth(request):
	logout(request)
	return redirect('/proyectos/')